<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>NAME</th>
          <th>ACTION</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{user.id}}</td>
          <td>{{user.name}}</td>
          <td>
            <button @click="Delete(user.id)">delete</button>
            <button @click="Modify(user.id)">modify</button>
          </td>
        </tr>
      </tbody>
    </table>
    <input v-model="input"/>
    <button @click="Create">新增</button>
    <div v-if="modify" class="update">
      <input v-model="update" />
      <button @click="Update">确认</button>
    </div>
  </div>
</template>

<script>
import Http from '@/utils/Http'
export default {
  data () {
    return {
      users: [],
      input: '',
      update: '',
      modify: false,
      modifyId: 0
    }
  },
  methods: {
    getData () {
      Http.get('/api/user', res => {
        this.users = res.data
      })
    },
    Create () {
      Http.post('/api/user', {
        name: this.input
      },
      res => {
        this.getData()
        this.input = ''
      })
    },
    Delete (id) {
      Http.delete(`/api/user/${id}`, {}, res => {
        this.getData()
      })
    },
    Modify (id) {
      this.modifyId = id
      this.modify = true
    },
    Update () {
      Http.post(`/api/user/${this.modifyId}`, {
        name: this.update
      },
      res => {
        this.getData()
        this.input = ''
        this.modify = false
      })
    }
  },
  mounted () {
    this.getData()
  }
}
</script>

